package com.bfxy.rocketmq.quickstart;

import com.bfxy.rocketmq.common.Contants;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.util.List;

/**
 * 消费者
 * @author 王毅
 */
@Slf4j
public class Consumer {

    private static String consumerGroupName="test_quick_consumer_name";

    public static void main(String[] args) throws MQClientException {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(consumerGroupName);
        consumer.setNamesrvAddr(Contants.NAMESRV_ADDR);
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
        consumer.setVipChannelEnabled(false);
        consumer.subscribe("test_quick_topic","*");
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                MessageExt message = msgs.get(0);
                try{
                    String topic = message.getTopic();
                    String tags = message.getTags();
                        String keys = message.getKeys();
//                    if("KeyA".equals(keys)){
//                        log.info("消息消费失败");
//                        int a=1/0;
//                    }
                    String msgBody = new String(message.getBody(), RemotingHelper.DEFAULT_CHARSET);
                    log.info("topic is {},tags is {},keys is {},msgBody is {}",topic,tags,keys,msgBody);
                    System.out.println("收到的消息是"+msgBody);
                }catch (Exception e){
                    e.printStackTrace();
                    log.info("times is {}",message.getReconsumeTimes());
                    if(message.getReconsumeTimes()==1){
                        log.info("消费失败次数超过限定次数");
                        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                    }
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        consumer.start();
        log.info("consumer started");
    }
}
